package com.sam.config;

import android.app.Application;
import android.content.Context;
import android.support.v4.app.FragmentManager;

import com.jess.arms.base.delegate.AppLifecycles;
import com.jess.arms.di.module.GlobalConfigModule;
import com.jess.arms.http.log.RequestInterceptor;
import com.jess.arms.integration.ConfigModule;
import com.sam.api.Api;
import com.sam.BuildConfig;

import java.util.List;
import java.util.concurrent.TimeUnit;

import me.jessyan.progressmanager.ProgressManager;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;

public class GlobalConfiguration implements ConfigModule {
    @Override
    public void applyOptions(Context context, GlobalConfigModule.Builder builder) {

        if (!BuildConfig.LOG_DEBUG) { //Release 时,让框架不再打印 Http 请求和响应的信息
            builder.printHttpLogLevel(RequestInterceptor.Level.NONE);
        }

        builder
                .baseurl(Api.BASE_URL)
                .globalHttpHandler(new GlobalHttpHandlerImpl())
                .responseErrorListener(new ResponseErrorListenerImpl())
                .gsonConfiguration((contextGson, gsonBuilder) -> {
                    gsonBuilder
                            .serializeNulls() //支持序列化为NULL
                            .enableComplexMapKeySerialization();//支持序列化key为object的map,默认只序列key为String的map
                })
                .okhttpConfiguration((contextOkHttp, okHttpBuilder) -> {
                    okHttpBuilder.writeTimeout(10, TimeUnit.MINUTES);
                    //使用一行代码监听 Retrofit／Okhttp 上传下载进度监听,以及 Glide 加载进度监听
                    //https://github.com/JessYanCoding/ProgressManager
                    ProgressManager.getInstance().with(okHttpBuilder);
                    //让 Retrofit 同时支持多个 BaseUrl 以及动态改变 BaseUrl
                    //https://github.com/JessYanCoding/RetrofitUrlManager
                    RetrofitUrlManager.getInstance().with(okHttpBuilder);
                })
                .rxCacheConfiguration((contextRxCache, rxCacheBuilder) -> {
                    //如果加载器不可用，则使用过期数据
                    rxCacheBuilder.useExpiredDataIfLoaderNotAvailable(true);
                    return null;
                });
    }


    /***
     * AppLication 配置
     * @param context
     * @param lifecycles
     */
    @Override
    public void injectAppLifecycle(Context context, List<AppLifecycles> lifecycles) {
        lifecycles.add(new AppLifecyclesImpl());
    }

    /***
     * 配置activity
     * @param context
     * @param lifecycles
     */

    @Override
    public void injectActivityLifecycle(Context context, List<Application.ActivityLifecycleCallbacks> lifecycles) {
        lifecycles.add(new ActivityLifecycleCallbacksImpl());
    }

    /***
     * 配置fragment
     * @param context
     * @param lifecycles
     */
    @Override
    public void injectFragmentLifecycle(Context context, List<FragmentManager.FragmentLifecycleCallbacks> lifecycles) {
        lifecycles.add(new FragmentLifecycleCallbacksExt());
    }
}
